/**
 * 表格打印工具函数
 */
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

/**
 * 将表格导出为PDF文件
 * @param {HTMLElement} element - 要导出的表格元素
 * @param {string} pdfName - 导出PDF的文件名
 */
export function exportTableToPdf(element, pdfName = '表格数据') {
  const dom = element.$el || element
  const box = window.getComputedStyle(dom)
  const width = parseFloat(box.width)
  const height = parseFloat(box.height)
  const scale = 2 // 缩放比例，提高清晰度

  // PDF的尺寸，A4纸的宽度是210mm
  const pdf = new JsPDF('p', 'pt', 'a4')
  const pdfWidth = pdf.internal.pageSize.getWidth()
  const pdfHeight = pdf.internal.pageSize.getHeight()
  const ratio = pdfWidth / width

  html2Canvas(dom, {
    scale,
    useCORS: true,
    allowTaint: true,
    logging: false,
    backgroundColor: '#FFFFFF'
  }).then(canvas => {
    const contentWidth = canvas.width
    const contentHeight = canvas.height
    
    // 一页PDF显示高度
    const pageHeight = contentWidth / pdfWidth * pdfHeight
    // 分页
    let leftHeight = contentHeight
    let position = 0
    const imgWidth = pdfWidth
    const imgHeight = pdfWidth / contentWidth * contentHeight

    const pageData = canvas.toDataURL('image/jpeg', 1.0)

    if (leftHeight < pageHeight) {
      // 不需要分页
      pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
    } else {
      // 需要分页
      while (leftHeight > 0) {
        pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
        leftHeight -= pageHeight
        position -= pdfHeight
        
        // 避免添加空白页
        if (leftHeight > 0) {
          pdf.addPage()
        }
      }
    }

    // 保存文件
    pdf.save(`${pdfName}.pdf`)
  })
}

/**
 * 打印表格元素
 * @param {HTMLElement} element - 要打印的表格元素
 * @param {string} title - 打印标题
 */
export function printTable(element, title = '表格数据') {
  const dom = element.$el || element
  const printWindow = window.open('', '_blank')
  
  // 创建打印内容
  const table = dom.cloneNode(true)
  
  // 创建样式
  const style = document.createElement('style')
  style.innerHTML = `
    body { font-family: Arial, sans-serif;width: 100%; }
    table { border-collapse: collapse; width: 100%; }
    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
    th { background-color: #f2f2f2; }
    .el-table__header-wrapper, .el-table__footer-wrapper { display: table-header-group; }
    .el-checkbox, .el-table__expand-icon { display: none; }
    @media print {
      body { margin: 0; padding: 15mm; }
      button { display: none; }
    }
  `
  
  // 设置打印页面
  printWindow.document.write('<html><head><title>打印表格</title></head><body>')
  printWindow.document.write(`<h2 style="text-align:center">${title}</h2>`)
  printWindow.document.head.appendChild(style)
  printWindow.document.body.appendChild(table)
  printWindow.document.write('</body></html>')
  
  printWindow.document.close()
  
  // 等待图片加载完成后打印
  printWindow.onload = function() {
    printWindow.print()
    printWindow.close()
  }
} 